const http = require('../http.js');

const constants = require('../constants.js');

const authentication = require('../authentication.js');

let setinad = null;

let rewardedVideoAd = null;

/**
 * @param {Object} that
 * @param {Object} fun
 */
function advertInfo(that,fun){
	var params = {
	    url: '/advert/adConfig',
	    method: 'GET',
	    data: {},
	    callBack: function (res) {
			if(res.code == 200){
				that.setData({
				    setAD: res.data
				});
				if(fun){
					fun()
				}
			}else{
				console.log('广告配置加载失败：'+ res.msg)
			}
	    }
	};
	http.request(params);
}

/**
 * 清除定时器
 */
function clearAdInterval(){
	clearInterval(setinad);
}

// 获取小程序插屏广告
function setInterstitialAd (that) {
	
	if (that.setAD.interstitialid && uni.createInterstitialAd) {
		console.log(that.setAD.interstitialid)
		let interstitialAd = uni.createInterstitialAd({
			adUnitId: that.setAD.interstitialid
		}); // 监听插屏错误事件

		interstitialAd.onError((err) => {
			console.error(err);
		});
			
		if (interstitialAd) {
			//暴力插屏2秒一次
			if (that.setAD.switchInad == 'yes') {
				setinad = setInterval(() => {
				interstitialAd.show().catch(err => {
				  console.error(err);
				});
			  }, 2000);
			} else {
			  setTimeout(() => {
				interstitialAd.show().catch(err => {
				  console.error(err);
				});
			  }, 6000);
			}
		}
	}
}

//加载激励广告
function loadRewardedVideoAd(that,succFun,errorFun){
	
	if (uni.createRewardedVideoAd) {
		console.log(that.setAD.rewardedVideoid)
		//#ifdef MP-KUAISHOU
		rewardedVideoAd = ks.createRewardedVideoAd({
		   type: that.setAD.adType,
		   unitId: that.setAD.rewardedVideoid,
		});
		//#endif
		
		//#ifdef MP-TOUTIAO || MP-WEIXIN
		rewardedVideoAd = uni.createRewardedVideoAd({
			adUnitId: that.setAD.rewardedVideoid,
		});
		//#endif
	
		console.log(rewardedVideoAd)
		try{
			if(rewardedVideoAd.closeHandler){
				rewardedVideoAd.offClose(rewardedVideoAd.closeHandler);
				console.log("rewardedVideoAd.offClose卸载成功");
			}
		} catch (e) {
			console.log("rewardedVideoAd.offClose 卸载失败");
			console.error(e);
		}
		
		rewardedVideoAd.closeHandler= function (res) {
			  // 用户点击了【关闭广告】按钮
			if (res && res.isEnded) {
				// 正常播放结束，可以下发游戏奖励
				console.log("正常播放结束，可以下发游戏奖励");
				//调用方法给用户奖励
				if(succFun){
					succFun()
				}
			} else {
				//提前关闭小广告
				console.log("提前关闭广告---不发奖励");
				if(errorFun){
					errorFun()
				}
			}
		};
		
		rewardedVideoAd.onError((err) => {
			console.log('广告拉取异常')
			console.log(err)
		})
		rewardedVideoAd.onClose(rewardedVideoAd.closeHandler);
	}
}

// 打开激励视频
function readMore(){
	
	if (rewardedVideoAd) {
		rewardedVideoAd.show().catch(err => {
			// 失败重试
			rewardedVideoAd.load().then(() => rewardedVideoAd.show())
		})
	}
}

/**看激励视频广告
 * @param {Object} self 
 */
function lookRewardedVideoAd(self,callMethodn){
	readMore();
	if(callMethodn){
		callMethodn()
	}
}


module.exports = {
    advertInfo,
	clearAdInterval,
	setInterstitialAd,
	loadRewardedVideoAd,
	readMore,
	lookRewardedVideoAd,
};